<template>
  <div class="swap-content">
    <div class="bag">
      <div class="swap">
        <div class="wsapHeader">
          <div class="time-container">
            <span class="title font-family">Crowdsale Ends after </span>
            <span class="time">{{countDown.day !== 0 ? countDown.day : '00'}} D {{countDown.hour >=10 ? countDown.hour :  countDown.hour}} H {{countDown.minute >=10 ? countDown.minute : '0' + countDown.minute}} M {{countDown.second >= 10 ? countDown.second :  countDown.second}} S</span>
          </div>
          <div class="progress">
            <el-progress :percentage="progress" :stroke-width="16"></el-progress>
          </div>
          <p class="leftSale font-medium">Left in Sale：{{leftSales}} AMT</p>
        </div>

        <div class="content">
          <!--  title部分      -->
          <div class="title">
            <p class="highlight font-family">Crowdsale</p>
            <p class="font-medium" style="font-size: 18px;line-height: 18px">Start At 04.07.2021 19:00 UTC</p>
          </div>
          <!--  from部分      -->
          <div class="from font-medium" :class="{'error': !isEnabledAmount && fromAmount}">
            <div class="top">
              <span>From</span>
              <span class="topSpan">
           <span>Balance：{{toFixed(bnbInfo.banlance) || '- -'}}</span>
            <span>Gas Fee：0.002</span>
            </span>

            </div>
            <div class="bottom">
              <NumberInput v-model="fromAmount" :min="minBNBBuyNum" :max="maxBNBBuyNum" :precision="3"
                           placeholder="Enter Amount" @blur="blurHandel()" @change="changeFromAmount"/>
              <div class="right">
                <span class="max font-medium" @click="fromAmount = bnbInfo.banlance - 0.002" v-if="bnbInfo.banlance">MAX</span>
                <span class="max font-medium gray"  v-else>MAX</span>
                <div class="icon">
                  <img src="@/assets/image/bnb.svg" alt="">
                </div>
                <span class="currency">BNB</span>
              </div>
            </div>
          </div>
          <!--  切换按钮      -->
          <div class="arrow">
            <img src="@/assets/image/arrow.png" alt="" style="width: 24px">
          </div>
          <!--  to部分      -->
          <div class="to font-medium">
            <div class="top">
              <span>To</span>
            </div>
            <div class="bottom">
              <NumberInput v-model="toAmount" :precision="3" placeholder="0.00" disabled/>
              <div class="logo">
                <img src="@/assets/image/logo.svg" alt="">
                <span class="currency font-medium">AMT</span>
              </div>
            </div>
          </div>

          <!--  兑换信息      -->
          <div class="swap-info font-medium">
            <p>Price：1 BNB = {{bnbToAmtRate}} AMT</p>
            <p>Left in Sale：{{leftSales}} AMT</p>
            <p>Swap Limit：At least 1 BNB</p>
          </div>

          <!--  按钮部分      -->
          <template v-if="pending">
            <button class="btn primary-button gray font-family">Pending <img style="height: 46px;width: 46px;" src="@/assets/image/pengding.gif" alt="">
            </button>
          </template>
          <template v-else>
            <button class="btn primary-button font-family" @click="changeNet" v-if="!isCurrentNet">Switch to BSC
            </button>
            <button class="btn primary-button  font-family" v-else-if="!fromAmount">Enter An Amount</button>
            <button class="btn primary-button  font-family" v-else-if="!currentAddress">Connect Wallet</button>
            <button class="btn primary-button  font-family" v-else-if="!isEnabledAmount">Wrong Amount</button>
            <button class="btn primary-button font-family" @click="swapHandel" v-else>Buy AMT</button>
          </template>
        </div>
        <div class="Amateras">
          <div class="content ">
            <!--  title部分      -->
            <div class="titles">
              <p class="highlight font-family">Amateras</p>
            </div>
            <div class="listSymble ">
              <div class="listSymblest font-medium">
                <div class="font-medium ">Symble</div>
                <div class="font-medium">AMT (Amateras)</div>
              </div>
              <div class="listSymblest font-medium">
                <div class=""><span class="spane font-medium">Total</span><span class="spansa font-medium">Supply</span>
                </div>
                <div class="font-medium">100,000,000 AMT</div>
              </div>
              <div class="listSymblest ">
                <div class="font-medium">Type</div>
                <div class="font-medium">BSC (BEP 20)</div>
              </div>
              <div class="listSymblest font-medium" style="border: none">
                <div class=""><span class="spans font-medium">Contract</span><span
                  class="spansr font-medium">Address</span></div>
                <div class="" >
                  <div class="SPAN">
                    <span class="addres font-medium">0x4ce5f6Bf8e996Ae54709C75865709ACA5127Dd54</span>
                    <img class="copy" @click="copy('0x4ce5f6Bf8e996Ae54709C75865709ACA5127Dd54')" src="@/assets/image/copy.jpg" alt="">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="showMessage">
        <BaseDialog :showDialog.sync="showMessage" v-bind="config">
          <div slot="content" class="content-wrapper">
            <img src="@/assets/image/success.png" alt="" class="swapStatus" v-if="swapStatus">
            <img src="@/assets/image/wrong.png" alt="" class="swapStatus" v-if="!swapStatus">
            <p v-html="swapStatusMsg" class="swapStatusMsg"></p>
          </div>
        </BaseDialog>
      </div>
    </div>
  </div>
</template>

<script>
import { filter } from '@/plugins/filters';
import { chainIdMap } from '@/utils/constants';
import { debounce } from '@/utils/common';
import api from '@/api/request';
import { mapState } from 'vuex';
import contract from '@/config/contract';
import NumberInput from '@/components/NumberInput';
import BaseDialog from '@/components/dialog/Index';
import { getLeftSales, getBanlance, swap, checkChain, toFixed, isWhitelisted } from '@/utils';

let timer = null;
let serverTimer = null;

export default {
  name: 'swap',
  data() {
    return {
      curDate: new Date().getTime(),
      fromAmount: '',
      toAmount: '',
      minBNBBuyNum: 1,
      leftSales: null,
      bnbToAmtRate: 1200,
      progress: 0,
      bnbInfo: {},
      pending: false,
      showMessage: false,
      config: {
        isShowBtn: false,
        wrapperClass: 'messageSwap',
      },
      swapStatus: false,
      swapStatusMsg: '',
    };
  },
  components: { NumberInput, BaseDialog },
  computed: {
    ...mapState(['chainId', 'currentAddress']),
    // 0 未开始 1 进行中 2 结束
    isbegin() {
      let num = 0;
      if (this.startTime <= this.curDate && this.curDate < this.endTime) {
        num = 1;
      } else if (this.curDate > this.endTime) {
        num = 2;
      }
      return num;
    },
    timezone() {
      return 'Asia/Tokyo';
    },
    dateFormat() {
      return 'YYYY-MM-DD HH:mm:ss';
    },
    startTime() {
      return moment.tz('2021-7-04 19:00:00', this.dateFormat, this.timezone).valueOf();
    },
    endTime() {
      return moment.tz('2021-7-07 08:59:59', this.dateFormat, this.timezone).valueOf();
    },
    countDown() {
      if (this.startTime >= this.curDate) {
        return filter.countDown((this.startTime - this.curDate) / 1000);
      }
      return filter.countDown((this.endTime - this.curDate) / 1000);
    },
    isCurrentNet() {
      return this.chainId === chainIdMap['BSC'];
    },
    maxBNBBuyNum() {
      return filter.toFixed(this.leftSales / this.bnbToAmtRate, 3);
    },
    isEnabledAmount() {
      return this.isCurrentNet
        && this.fromAmount
        && this.currentAddress
        && Number(this.fromAmount) <= (Number(this.bnbInfo?.banlance) - 0.002)
        && Number(this.fromAmount) >= Number(this.minBNBBuyNum)
        && Number(this.fromAmount) <= Number(this.maxBNBBuyNum);
    },
  },
  async mounted() {
    this.getTime();
    // 每10s获取服务器时间
    if (serverTimer) clearInterval(serverTimer);
    serverTimer = setInterval(() => {
      this.getTime();
    }, 10000);
    if (timer) clearInterval(timer);
    timer = setInterval(() => {
      this.curDate += 1000;
    }, 1000);
  },
  destroyed() {
    if (timer) clearInterval(timer);
    if (serverTimer) clearInterval(serverTimer);
  },
  watch: {
    currentAddress: {
      immediate: true,
      handler(val) {
        if (!this.isCurrentNet || !val) {
          this.bnbInfo.banlance = '';
          return;
        }
        this.init();
      },
    },
    isCurrentNet: {
      immediate: true,
      handler(val) {
        if (!this.currentAddress || !val) {
          this.bnbInfo.banlance = '';
          return;
        }
        this.init();
      },
    },
    isbegin() {
      this.checkStatus();
    },
  },
  methods: {
    getTime() {
      api.getTimestamp().then(({ t }) => {
        this.curDate = Number(t);
        this.checkStatus();
      });
    },
    // 检测时间
    checkStatus() {
      if (this.isbegin === 2) this.$router.push('/swap/end');
      if (this.isbegin === 0) this.$router.push('/swap/countdown');
    },
    async init() {
      this.leftSales = await getLeftSales(contract.presale.abi, contract.presale.address);
      this.progress = toFixed(($big(10000000).sub($big(this.leftSales))).div($big(2000000)) * $big(100), 2);
      this.bnbInfo = await getBanlance({ account: this.currentAddress, chain: 'BSC', currency: 'BNB' });
    },
    clearForm() {
      this.fromAmount = this.toAmount = '';
    },
    blurHandel() {
      this.fromAmount = Number(this.fromAmount) === 0 ? '' : this.fromAmount;
    },
    getChangeFromAmountFun: debounce(async function () {
      if (Number(this.fromAmount) <= 0) {
        this.toAmount = '';
        return;
      }
      const { toFixed } = this.$options.filters;

      this.toAmount = toFixed(this.fromAmount * this.bnbToAmtRate, 3);
    }, 1000),
    changeFromAmount() {
      this.getChangeFromAmountFun();
    },
    async changeNet() {
      await checkChain({ target: 'BSC' });
      this.bnbInfo = await getBanlance({ account: this.currentAddress, chain: 'BSC', currency: 'BNB' });
    },
    async swapHandel() {
      this.pending = true;
      const isWhite = await isWhitelisted(contract.presale.abi, contract.presale.address, this.currentAddress);
      if (!isWhite) {
        this.$message.error('Your address isn’t in the whitelist');
        this.pending = false;
        return;
      }
      swap({
        from: this.currentAddress,
        to: contract.presale.address,
        amount: this.fromAmount,
      }).then(async res => {
        if (res.type === 'success') {
          this.showMessage = true;
          this.swapStatus = true;
          this.swapStatusMsg = `Buy <i class="font-semiBold" style="color: #eb6930">${this.toAmount} AMT</i> Successed!`;
          this.bnbInfo = await getBanlance({ account: this.currentAddress, chain: 'BSC', currency: 'BNB' });
          this.init();
          this.clearForm();
        } else {
          this.showMessage = true;
          this.swapStatus = false;
          this.swapStatusMsg = `Buy <i class="font-semiBold" style="color: #eb6930">${this.toAmount} AMT</i> Failed!`;
        }
        this.pending = false;
      });
    },
  },
};
</script>

<style lang="scss">
  .dialogCustomer.messageSwap .el-dialog__header {
    border-bottom: none;
  }

  .dialogCustomer.messageSwap {
    .content-wrapper {
      text-align: center;
      margin-left: 0;

      img {
        margin-left: 0;
      }
    }

    .el-dialog__header {
      padding: 0px;
    }

    .el-dialog__body {
      padding-top: 0 !important;
    }

    .swapStatus {
      width: 88px;
      margin-bottom: 46px;
      margin-top: 60px;
    }

    .swapStatusMsg {
      font-size: 24px;
      margin-bottom: 30px;
    }

    i {
      font-size: 24px;
    }
  }
</style>

<style lang="scss" scoped>
  @import '@/style/variable.scss';

  .swap-content {
    text-align: center;
    width: 100%;
    padding: 0 30px;
    box-sizing: border-box;
    background: url("../../assets/image/bg.svg");
    background-repeat: no-repeat;
    background-attachment: scroll;
    background-size: cover;
    .swap {
      width: 60%;
      margin: 0 auto 0;
      padding-top: 5px;
    }

    .wsapHeader {
      border-radius: 20px;
      background-color: $bg-color;
      margin-bottom: 30px;
      z-index: 9999;
    }

    .time-container {
      margin-top: 30px;
      padding: 60px 0 26px 0;

      .title {
        font-weight: bold;
        font-size: 32px;
        color: $text-color;
      }

      .time {
        font-weight: bold;
        font-size: 32px;
        background: $text-color;
        -webkit-background-clip: text;
        color: $global-primary;
      }
    }

    .progress {
      width: 70%;
      height: 16px;
      margin: 0 auto;
      margin-bottom: 48px;
      ::v-deep .el-progress-bar__outer {
        background-color: rgba(235, 105, 48, .1);
        overflow: initial;
      }

      ::v-deep .el-progress-bar__inner {
        background: $global-primary;
      }

      ::v-deep .el-progress-bar__inner::after {
        content: ' ';
        display: inline-block;
        width: 34px;
        height: 40px;
        position: absolute;
        z-index: 999;
        right: -8px;
        top: -12px;
        background-image: url("../../assets/image/progress.png");
        background-size: 34px 40px;
      }

      ::v-deep .el-progress {
        display: flex;
      }

      ::v-deep .el-progress .el-progress__text {
        font-weight: bold;
        font-size: 24px!important;
        color: #FFFFFF!important;
        position: relative;
        bottom:4px;
        margin-left: 20px;
      }
    }

    .leftSale {
      padding-bottom: 40px;
      font-weight: 500;
      font-size: 24px;
      line-height: 17px;
      color: #FFFFFF;
    }

    .Amateras {
      padding: 30px 0;
    }

    .content {
      margin: 0 auto;
      padding-bottom: 40px;
      box-sizing: border-box;
      border-radius: 20px;
      background: $bg-color;
      position: relative;


      .from, .to {
        font-size: 14px;
        height: 130px;
        box-sizing: border-box;
        border-radius: 20px;
        margin: 0 30px;
        padding: 30px 20px 20px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        background: $theme;

        &.error {
          border: 1px solid #EE7358;

          ::v-deep .el-input__inner {
            color: #EE7358;
          }
        }

        .top, .bottom {
          display: flex;
          justify-content: space-between;
        }

        .top {
          span {
            font-weight: bold;
            color: #646E78;
          }

          .topSpan {
            padding-bottom: 20px;

            span {
              display: block;
              text-align: right;
              line-height: 20px;
            }
          }
        }

        .bottom {
          .right {
            display: flex;
            align-items: center;

            .max {
              cursor: pointer;
              color: $global-primary;
              font-size: 22px;
              position: relative;
              right: 10px;
            }

            .max.gray {
              opacity: 0.4;
            }

            .icon {
              margin: 0 10px;
            }

            img {
              width: 32px;
              height: 32px;
            }
          }
        }

        .currency {
          font-weight: 500;
          font-size: 24px;
        }

        .logo {
          display: flex;
          align-items: center;

          img {
            width: 32px;
          }
          .currency {
            margin-left: 10px;
          }
        }
      }

      .arrow {
        margin: 29px 0 32px 0;
      }

      .to {
        box-sizing: border-box;
        margin-bottom: 35px;
      }

      .swap-info {
        margin: 0 0 35px 50px;

        p {
          font-weight: bold;
          text-align: left;
          margin-bottom: 20px;

          &:last-child {
            margin-bottom: 0px;
          }
        }
      }

      // 头部
      .title {
        height: 116px;
        padding: 30px;
        box-sizing: border-box;
        margin-bottom: 30px;
        text-align: left;
        border-bottom: 1px solid $theme;

        .highlight {
          color: $global-primary;
          font-size: 24px;
          margin-bottom: 16px;
          font-weight: bold;
        }
      }

      // 头部
      .titles {
        height: 79px;
        padding: 30px;
        box-sizing: border-box;
        margin-bottom: 30px;
        text-align: left;
        border-bottom: 1px solid $theme;

        .highlight {
          color: $global-primary;
          font-size: 24px;
          margin-bottom: 16px;
          font-weight: bold;
        }
      }

      .listSymble {
        padding-left: 30px;

        .listSymblest {
          display: flex;
          justify-content: space-between;
          padding: 30px 0;
          border-bottom: 2px dashed #6B7C8D;
          align-items: center;

          div {
            text-align: left;
            font-weight: 500;
            font-size: 18px;
            line-height: 18px;
            color: #FFFFFF;

            &:nth-child(1) {
              /*flex: 1;*/
              width: 35%;
              text-align: left;

              span {
                display: inline-block;
                font-weight: 500;
                font-size: 18px;
                line-height: 27px;
                color: #FFFFFF;
              }

              .spane {
                width: 50px;
                display: inline-block;
              }

              .spans {
                width: 90px;
                display: inline-block;
              }

              .spansr {
                width: 66%;
                display: inline-block;
              }

              .spansa {
                width: 75%;
                display: inline-block;
              }
            }

            &:nth-child(2) {
              text-align: left;
              width: 65%;
              .SPAN {
                width: 70%;
                display: flex;
                align-items: center;
                .addres {
                  width: 100%;
                  display: inline-block;
                  font-weight: 500;
                  font-size: 18px;
                  line-height: 27px;
                  color: #FFFFFF;
                  word-wrap: break-word;
                  padding-right: 15px;
                }
              }
            }
          }
        }
      }

      // 美女和萌宠
      .beauty {
        position: absolute;
        left: -224px;
        bottom: -56px;
      }

      .cute-pet {
        position: absolute;
        right: -70px;
        top: -50px;
      }
    }

    .btn {
      font-weight: bold;
      font-size: 24px;
      margin: 0 auto;
      width: 90%;
      display: flex;
      align-items: center;
      text-align: center;
      justify-content: center;
    }

    .btn.gray {
      opacity: 0.4;
      cursor: not-allowed;
    }
  }
</style>
